package com.lwt.yygh.common.result;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.sql.ResultSet;

/**
 * @Author Weton Li
 * @Date 2021/4/5 14:28
 */
@Data
@ApiModel("全局返回类型(统一结果)")
public class Result<T> {

    @ApiModelProperty("返回码")
    private Integer code;
    @ApiModelProperty("返回消息")
    private String message;
    @ApiModelProperty("返回数据")
    private T data; // 这里是date属性，而不是data

    public Result(){

    }

    protected static <T> Result<T> build(T data){
        Result<T> result = new Result<T>();
        if (data != null) {
            result.setData(data);
        }
        return result;
    }

    public static <T> Result<T> build(T body,ResultCodeEnum resultCodeEnum){
        Result<T> result = build(body);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMessage());
        return result;
    }

    public static <T> Result<T> build(Integer code,String message){
        Result<T> result = build(null);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    /**
     * ok不传参
     * @param <T>
     * @return
     */
    public static <T> Result<T> ok(){
        return Result.ok(null);
    }

    /**
     * ok传参
     * @param data
     * @param <T>
     * @return 返回值继续调用build(T body,ResultCodeEnum resultCodeEnum)，去设置成功的date、code、message
     */
    public static <T> Result<T> ok(T data){
        Result<T> result = build(data);
        return build(data,ResultCodeEnum.SUCCESS);
    }

    /**
     * fail不传参
     * @param <T>
     * @return
     */
    public static <T> Result<T> fail(){
        return Result.fail(null);
    }

    /**
     * fail传参
     * @param data
     * @param <T>
     * @return 返回值继续调用build(T body,ResultCodeEnum resultCodeEnum)，去设置失败的date、code、message
     */
    public static <T> Result<T> fail(T data){
        Result<T> result = build(data);
        return build(data,ResultCodeEnum.FAIL);
    }

    public Result<T> message(String msg){
        this.setMessage(msg);
        return this;
    }

    public Result<T> code(Integer code){
        this.setCode(code);
        return this;
    }

    public boolean isOk(){
        if (this.getCode().intValue() == ResultCodeEnum.SUCCESS.getCode().intValue()) {
            return true;
        }
        return false;
    }

}
